/* $Id: TournamentXmlWriter.java 39 2009-07-24 22:48:06Z h_m_r@gmx.de $ */
package org.jugger.tournament.model.writer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.util.HashMap;

import org.jugger.tournament.model.Match;
import org.jugger.tournament.model.Round;
import org.jugger.tournament.model.Team;
import org.jugger.tournament.model.Tournament;

import util.XMLWriter;
import util.XMLWriter.XMLWriterException;

public class TournamentXmlWriter {
	public static boolean writeToXML(URI uri, Tournament tournament) {

		try {

			File f = new File(uri);

			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
			XMLWriter xmlWriter = new XMLWriter(writer, "\t");

			xmlWriter.beginElement("tournament").addAttribute("version", 1);

			xmlWriter.beginElement("scoreCalculator").addAttribute("type", tournament.getScoreCalculator().getPrefix()).endElement();
			xmlWriter.beginElement("rankingComparator").addAttribute("type", tournament.getRankingComparator().getPrefix()).endElement();

			// create team map (team => number)
			xmlWriter.beginElement("teams");
			HashMap<Team, Integer> teams = new HashMap<Team, Integer>();
			for(Team team: tournament.getTeams()) {
				teams.put(team, teams.size());
				xmlWriter.beginElement("team").addAttribute("name", team.getName()).addAttribute("city", team.getCity()).endElement();
			}
			xmlWriter.endElement();

			xmlWriter.beginElement("rounds");

			for(Round round: tournament.getRounds()) {
				xmlWriter.beginElement("round");

				for(Match match: round) {
					xmlWriter.beginElement("match");
					xmlWriter.addAttribute("teamA", teams.get(match.getTeamA()));
					xmlWriter.addAttribute("teamB", teams.get(match.getTeamB()));
					xmlWriter.addAttribute("pointsA", match.getPointsA());
					xmlWriter.addAttribute("pointsB", match.getPointsB());
					xmlWriter.addAttribute("finished", match.isFinished());
					xmlWriter.endElement();
				}

				xmlWriter.endElement();
			}

			xmlWriter.endElement();
			xmlWriter.endElement();

			writer.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XMLWriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}
}
